package com.nio;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;

/**
 * @description
 * @author: wangtao
 * @date:17:06 2018/12/20
 * @email:taow02@jumei.com
 */
@ChannelHandler.Sharable //1
public class EchoServerHandler extends ChannelHandlerAdapter {
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		ByteBuf in = (ByteBuf) msg;
		String msgStr = in.toString(CharsetUtil.UTF_8);
		String fromName = msgStr.split(":")[0];
		String toName = msgStr.split(":")[1];
		System.out.println("Server received: " + msgStr);
		CtxManager.addCtx(fromName, ctx);
		ChannelHandlerContext toCtx = CtxManager.getCtx(toName);
		if (toCtx == null) {
			System.out.println("ctx is not online");
		} else {
			toCtx.writeAndFlush(Unpooled.copiedBuffer(msgStr, //2
					CharsetUtil.UTF_8));
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		//		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)//4
		//				//通知client关闭连接
		//				.addListener(ChannelFutureListener.CLOSE);
		//客户端不关闭连接
		ctx.flush();
		System.out.println("server read complete");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace(); //5
		ctx.close(); //6
	}
}